/*********************************************************
 *********************************************************
 ********************                  *******************
 *************                                ************
 *******                  _oo0oo_                  *******
 ***                     o8888888o                     ***
 *                       88" . "88                       *
 *                       (| -_- |)                       *
 *                       0\  =  /0                       *
 *                     ___/`---'\___                     *
 *                   .' \\|     |// '.                   *
 *                  / \\|||  :  |||// \                  *
 *                 / _||||| -:- |||||- \                 *
 *                |   | \\\  -  /// |   |                *
 *                | \_|  ''\---/''  |_/ |                *
 *                \  .-\__  '-'  ___/-. /                *
 *              ___'. .'  /--.--\  `. .'___              *
 *           ."" '<  `.___\_<|>_/___.' >' "".            *
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |          *
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /          *
 *      =====`-.____`.___ \_____/___.-`___.-'=====       *
 *                        `=---='                        *
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      *
 *********__佛祖保佑__永无BUG__验收通过__钞票多多__*********
 *********************************************************/
package org.jbase.oauth.sevice;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.jbase.oauth.QqConfig;
import org.jbase.oauth.WechatConfig;
import org.springframework.stereotype.Service;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.QqAccessToken;
import com.qq.connect.utils.RandomStatusGenerator;
import com.qq.connect.utils.http.PostParameter;

import weibo4j.Oauth;
import weibo4j.http.SinaWeiboAccessToken;
import weibo4j.model.WeiboException;

/**
 * Project: yxt_common <br/>
 * File: OauthService.java <br/>
 * Class: org.jbase.common.service.OauthService <br/>
 * Description: <描述类的功能>. <br/>
 * Copyright: Copyright (c) 2011 <br/>
 * Company: http://www.yxtsoft.com/ <br/>
 * Makedate: 2016年7月1日 下午5:41:02 <br/>
 * 
 * @author liuzhanhong
 * @version 1.0
 * @since 1.0
 */
@Service
public class OauthService {

	private com.qq.connect.utils.http.HttpClient qqclient = new com.qq.connect.utils.http.HttpClient();

	public enum OauthFrom {
		QQ, Wechat, SinaWeibo;
	}

	public String buildAuthorizeURL(OauthFrom from, HttpServletRequest request) {
		String url = null;

		switch (from) {
		case QQ:
			url = buildQQAuthorizeURL(request);
			break;
		case Wechat:
			url = buildWechatAuthorizeURL(request);
			break;
		case SinaWeibo:
			url = buildSinaWeiboAuthorizeURL();
			break;
		default:
			break;
		}
		return url;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param request
	 * @return
	 */
	public String buildQQAuthorizeURL(HttpServletRequest request) {

		String state = RandomStatusGenerator.getUniqueState();
		request.getSession().setAttribute("qq_connect_state", state);

		String url = QqConfig.getValue("authorizeURL") + "?client_id=" + QqConfig.getValue("app_ID") + "&redirect_uri="
				+ QqConfig.getValue("redirect_URI") + "&response_type=code" + "&state=" + state;

		String scope = QqConfig.getValue("scope");
		if ((scope != null) && (!scope.equals(""))) {
			url = url + "&scope=" + scope;
		}
		return url;

	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param request
	 * @return
	 */
	public String buildWechatAuthorizeURL(HttpServletRequest request) {
		String value = WechatConfig.getValue("authorizeURL");

		return value
				+ "?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @return
	 */
	public String buildSinaWeiboAuthorizeURL() {
		String url = "";
		Oauth oauth = new Oauth();
		try {
			url = oauth.authorize("code");
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return url;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param request
	 * @return
	 */
	public SinaWeiboAccessToken getWeiboAccessToken(HttpServletRequest request) {
		String code = request.getParameter("code");
		SinaWeiboAccessToken accessTokenByCode = null;
		Oauth oauth = new Oauth();
		try {
			accessTokenByCode = oauth.getAccessTokenByCode(code);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return accessTokenByCode;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param request
	 * @return
	 */
	public UserInfo getQzoneUserInfo(HttpServletRequest request) {
		QqAccessToken accessTokenObj = null;
		UserInfo qzoneUserInfo = null;
		try {
			accessTokenObj = getQqAccessToken(request);

			String accessToken = null, openID = null;
			long tokenExpireIn = 0L;

			// 我们的网站被CSRF攻击了或者用户取消了授权
			// 做一些数据统计工作
			if (accessTokenObj.getAccessToken().equals(""))
				return null;
			accessToken = accessTokenObj.getAccessToken();
			tokenExpireIn = accessTokenObj.getExpireIn();

			request.getSession().setAttribute("ourpyw_qq_access_token", accessToken);
			request.getSession().setAttribute("ourpyw_qq_token_expirein", String.valueOf(tokenExpireIn));

			// 利用获取到的accessToken 去获取当前用的openid -------- start
			OpenID openIDObj = new OpenID(accessToken);
			openID = openIDObj.getUserOpenID();

			request.getSession().setAttribute("ourpyw_qq_openid", openID);
			// 利用获取到的accessToken 去获取当前用户的openid --------- end

			qzoneUserInfo = new UserInfo(accessToken, openID);
		} catch (QQConnectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return qzoneUserInfo;

	}

	public QqAccessToken getQqAccessToken(HttpServletRequest request) throws QQConnectException {

		String queryString = request.getQueryString();
		if (queryString == null) {
			return new QqAccessToken();
		}
		String state = (String) request.getSession().getAttribute("qq_connect_state");
		if ((state == null) || (state.equals(""))) {
			return new QqAccessToken();
		}

		Matcher m = Pattern.compile("code=(\\w+)&state=(\\w+)&?").matcher(queryString);
		String returnAuthCode = "";
		String returnState = "";
		if (m.find()) {
			returnAuthCode = m.group(1);
			returnState = m.group(2);
		}

		QqAccessToken accessTokenObj = null;

		if ((returnState.equals("")) || (returnAuthCode.equals(""))) {
			accessTokenObj = new QqAccessToken();

		} else if (!state.equals(returnState)) {
			accessTokenObj = new QqAccessToken();
		} else {
			accessTokenObj = new QqAccessToken(this.qqclient.post(QqConfig.getValue("accessTokenURL"),
					new PostParameter[] { new PostParameter("client_id", QqConfig.getValue("app_ID")),
							new PostParameter("client_secret", QqConfig.getValue("app_KEY")),
							new PostParameter("grant_type", "authorization_code"),
							new PostParameter("code", returnAuthCode),
							new PostParameter("redirect_uri", QqConfig.getValue("redirect_URI")) },
					Boolean.valueOf(false)));
		}

		return accessTokenObj;

	}

}
